import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler, MinMaxScaler
from typing import Dict, List, Any


class HardwareFeatureEngineer:
    """
    硬件特征工程类
    """
    
    def __init__(self):
        self.scaler = StandardScaler()
    
    def extract_battery_features(self, df: pd.DataFrame) -> pd.DataFrame:
        """
        提取电池相关特征
        """
        # 计算电压相关特征
        if 'avg_voltage' in df.columns and 'voltage_drop_rate' in df.columns:
            df['voltage_risk_score'] = df['voltage_drop_rate'] / (df['avg_voltage'] + 0.001)
        
        # 基于使用天数和电压的复合特征
        if 'days_in_use' in df.columns and 'avg_voltage' in df.columns:
            df['age_voltage_ratio'] = df['days_in_use'] / (df['avg_voltage'] + 0.001)
        
        # 信号强度和电压的相关性特征
        if 'signal_strength_avg' in df.columns and 'avg_voltage' in df.columns:
            # 信号强度通常为负值，转换为正值进行计算
            df['signal_voltage_interaction'] = (-df['signal_strength_avg']) * df['avg_voltage']
        
        return df
    
    def extract_screen_features(self, df: pd.DataFrame) -> pd.DataFrame:
        """
        提取屏幕相关特征
        """
        # 计算屏幕使用强度
        if 'screen_refresh_count' in df.columns and 'days_in_use' in df.columns:
            # 避免除以零
            df['daily_refresh_rate'] = df['screen_refresh_count'] / (df['days_in_use'] + 1)
        
        # 温度波动对屏幕的影响
        if 'temp_var' in df.columns:
            df['high_temp_risk'] = (df['temp_var'] > 15).astype(int)
        
        return df
    
    def normalize_features(self, df: pd.DataFrame, feature_columns: List[str]) -> pd.DataFrame:
        """
        标准化特征
        """
        # 只选择存在的列
        available_features = [col for col in feature_columns if col in df.columns]
        df[available_features] = self.scaler.fit_transform(df[available_features])
        return df
    
    def build_features(self, df: pd.DataFrame) -> pd.DataFrame:
        """
        构建完整的硬件特征集
        """
        df = self.extract_battery_features(df)
        df = self.extract_screen_features(df)
        
        # 选择需要标准化的数值特征
        numeric_features = ['days_in_use', 'avg_voltage', 'voltage_drop_rate', 
                           'signal_strength_avg', 'screen_refresh_count', 
                           'temp_max', 'temp_min', 'temp_var']
        
        # 添加新生成的特征
        numeric_features.extend(['voltage_risk_score', 'age_voltage_ratio', 
                               'signal_voltage_interaction', 'daily_refresh_rate'])
        
        df = self.normalize_features(df, numeric_features)
        
        return df


class SoftwareFeatureEngineer:
    """
    软件特征工程类
    """
    
    def __init__(self):
        self.scaler = MinMaxScaler()
    
    def extract_error_features(self, df: pd.DataFrame) -> pd.DataFrame:
        """
        提取错误相关特征
        """
        # 计算总错误数
        error_columns = [col for col in df.columns if col.startswith('error_')]
        if error_columns:
            df['total_error_count'] = df[error_columns].sum(axis=1)
            df['error_diversity'] = (df[error_columns] > 0).sum(axis=1)
        
        # 网络错误占比
        if 'error_NET_TIMEOUT' in df.columns and 'total_error_count' in df.columns:
            # 避免除以零
            df['network_error_ratio'] = df['error_NET_TIMEOUT'] / (df['total_error_count'] + 0.001)
        
        return df
    
    def extract_performance_features(self, df: pd.DataFrame) -> pd.DataFrame:
        """
        提取性能相关特征
        """
        # 重启与网络重试的相关性
        if 'reboot_count' in df.columns and 'network_retry_ratio' in df.columns:
            df['reboot_network_risk'] = df['reboot_count'] * df['network_retry_ratio']
        
        # 日志熵与心跳间隔的综合指标
        if 'log_entropy' in df.columns and 'heartbeat_interval_std' in df.columns:
            df['system_instability_score'] = df['log_entropy'] * df['heartbeat_interval_std']
        
        return df
    
    def normalize_features(self, df: pd.DataFrame, feature_columns: List[str]) -> pd.DataFrame:
        """
        标准化特征
        """
        available_features = [col for col in feature_columns if col in df.columns]
        df[available_features] = self.scaler.fit_transform(df[available_features])
        return df
    
    def build_features(self, df: pd.DataFrame) -> pd.DataFrame:
        """
        构建完整的软件特征集
        """
        df = self.extract_error_features(df)
        df = self.extract_performance_features(df)
        
        # 选择需要标准化的数值特征
        numeric_features = ['heartbeat_interval_std', 'reboot_count', 
                           'network_retry_ratio', 'log_entropy']
        
        # 添加新生成的特征
        numeric_features.extend(['total_error_count', 'error_diversity', 
                               'network_error_ratio', 'reboot_network_risk', 
                               'system_instability_score'])
        
        df = self.normalize_features(df, numeric_features)
        
        return df


class TicketFeatureEngineer:
    """
    工单特征工程类
    """
    
    def __init__(self):
        self.scaler = MinMaxScaler()
    
    def extract_hardware_keywords(self, df: pd.DataFrame) -> pd.DataFrame:
        """
        提取硬件相关关键词特征
        """
        hardware_keywords = ['keyword_黑屏', 'keyword_电池', 'keyword_发热']
        available_hardware = [col for col in hardware_keywords if col in df.columns]
        if available_hardware:
            df['hardware_issue_score'] = df[available_hardware].mean(axis=1)
        
        return df
    
    def extract_software_keywords(self, df: pd.DataFrame) -> pd.DataFrame:
        """
        提取软件相关关键词特征
        """
        software_keywords = ['keyword_刷新慢', 'keyword_闪退', 'keyword_联网']
        available_software = [col for col in software_keywords if col in df.columns]
        if available_software:
            df['software_issue_score'] = df[available_software].mean(axis=1)
        
        return df
    
    def normalize_features(self, df: pd.DataFrame, feature_columns: List[str]) -> pd.DataFrame:
        """
        标准化特征
        """
        available_features = [col for col in feature_columns if col in df.columns]
        df[available_features] = self.scaler.fit_transform(df[available_features])
        return df
    
    def build_features(self, df: pd.DataFrame) -> pd.DataFrame:
        """
        构建完整的工单特征集
        """
        df = self.extract_hardware_keywords(df)
        df = self.extract_software_keywords(df)
        
        # 获取所有关键词特征
        keyword_features = [col for col in df.columns if col.startswith('keyword_')]
        
        # 添加新生成的特征
        keyword_features.extend(['hardware_issue_score', 'software_issue_score'])
        
        df = self.normalize_features(df, keyword_features)
        
        return df


def get_feature_importance(model, feature_names: List[str]) -> Dict[str, float]:
    """
    获取特征重要性
    
    Args:
        model: 训练好的模型
        feature_names: 特征名称列表
    
    Returns:
        特征重要性字典
    """
    importance = model.feature_importances_
    feature_importance = {}
    
    for i, feature in enumerate(feature_names):
        if i < len(importance):
            feature_importance[feature] = float(importance[i])
    
    # 按重要性排序
    sorted_importance = {k: v for k, v in sorted(feature_importance.items(), 
                                               key=lambda item: item[1], 
                                               reverse=True)}
    
    return sorted_importance
